﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YunSpace.Application.SystemManage;
using YunSpace.Core;
using YunSpace.Data;
using YunSpace.Domain.Entity.OrderMgr;
using YunSpace.Domain.Entity.SystemManage;
using YunSpace.Domain.IRepository.OrderMgr;
using YunSpace.Domain.ViewModel.Sale;
using YunSpace.Repository.OrderMgr;

namespace YunSpace.Application.OrderFlowManage
{
    public class SiteOrderSalesReportApp
    {
        IOrderSalesReportRepository salesReportApp = new OrderSalesReportRepository();

        public void InsertEntity(string orderId, string F_OrderStep,string F_Id, SiteOrderSalesReportModel salesreport) {
            OrderSalesReportEntity entity = salesReportApp.FindEntity(F_Id);
            if (entity == null)
            {
                entity = new OrderSalesReportEntity();
                entity.Create();
                entity.F_OrderId = orderId;
                entity.F_OrderState = F_OrderStep;
                entity.F_ReportTitle = salesreport.F_ReportTitle;
                entity.F_Context = salesreport.F_Context;
                salesReportApp.Insert(entity);
            }
            else {
                entity.F_ReportTitle = salesreport.F_ReportTitle;
                entity.F_Context = salesreport.F_Context;
                salesReportApp.Update(entity);
            }                       
        }

        public OrderSalesReportEntity GetSaleReportEntity(string F_Id) {
            OrderSalesReportEntity entity = salesReportApp.FindEntity(F_Id);
            return entity;
        }

        public List<OrderSalesReportViewModel> GetSaleReportGridHistoryData(Pagination pagination, string queryJson) {
            List<OrderSalesReportViewModel> reslut = new List<OrderSalesReportViewModel>();
            using (var db = new RepositoryBase())
            {
                var sqlStr = @"select  a.F_Id,c.F_Id F_DemandId,a.F_OrderId,c.F_ActivityTheme,date_format(c.F_ActivityStartDate, '%Y-%m-%d') F_ActivityStartDate,c.F_DemandCash,
                                date_format(c.F_ActivityEndDate, '%Y-%m-%d') F_ActivityEndDate,d.F_RealName,a.F_ReportTitle,a.F_Context,
                                a.F_CreatorTime,a.F_OrderState  from Site_Order_SalesReport a
                                inner join Site_Client_Order b on a.F_OrderId=b.F_Id
                                inner join Site_Clients_ProjectByDemand c on b.F_DemandId=c.F_Id
                                inner join Sys_User d on a.F_CreatorUserId=d.F_Id where 1=1 {0} {1} {2} {3} {4} order by a.F_CreatorTime desc";
                var queryParam = queryJson.ToJObject();

                ///获取用户权限
                var LoginInfo = OperatorProvider.Provider.GetCurrent();
                RoleApp role = new RoleApp();
                RoleEntity roleEntity = role.GetForm(LoginInfo.RoleId);
                OrganizeApp organize = new OrganizeApp();
                OrganizeEntity organizeEntity = organize.GetForm(LoginInfo.DepartmentId);

                string F_GroupId = "";
                if (queryParam["F_Type"].ToString() != "self")
                {
                    if (roleEntity.F_EnCode == "1006" || roleEntity.F_EnCode == "1012")
                    {
                        F_GroupId += " and d.F_GroupId='" + LoginInfo.F_GroupId + "'";
                    }
                    else if (roleEntity.F_EnCode == "1004")
                    {
                        F_GroupId += " and d.F_GroupId='" + LoginInfo.F_GroupId + "' and d.F_Id='" + LoginInfo.F_GroupId + "'";
                    }
                }

                DbParameter[] parameter =
               {
                    new MySqlParameter("@F_StartTime", queryParam["F_StartTime"]),
                    new MySqlParameter("@F_EndTime", queryParam["F_EndTime"]),
                    new MySqlParameter("@F_Type",queryParam["F_Type"]),
                    new MySqlParameter("@F_DemandId",queryParam["F_DemandId"]),
                };

                sqlStr = string.Format(sqlStr, F_GroupId,
                    queryParam["F_StartTime"].IsEmpty() ? "" : " and a.F_CreatorTime>@F_StartTime",
                    queryParam["F_EndTime"].IsEmpty() ? "" : " and a.F_CreatorTime<@F_EndTime",
                    queryParam["F_Type"].ToString() == "self" ? " and a.F_CreatorUserId='" + LoginInfo.UserId + "'" : "",
                    queryParam["F_DemandId"].IsEmpty() ? "" : " and c.F_Id=@F_DemandId"
                    );
                reslut = db.FindList<OrderSalesReportViewModel>(sqlStr, parameter, pagination);
            }
            return reslut;
        }

        public List<OrderSalesReportViewModel> GetSaleReportGridData(Pagination pagination, string queryJson) {
            List<OrderSalesReportViewModel> reslut = new List<OrderSalesReportViewModel>();
            using (var db = new RepositoryBase())
            {
                var sqlStr = @"select  a.F_Id,c.F_Id F_DemandId,a.F_OrderId,c.F_ActivityTheme,date_format(c.F_ActivityStartDate, '%Y-%m-%d') F_ActivityStartDate,c.F_DemandCash,
                                date_format(c.F_ActivityEndDate, '%Y-%m-%d') F_ActivityEndDate,d.F_RealName,a.F_ReportTitle,a.F_Context,
                                a.F_CreatorTime,a.F_OrderState,
                                case when cast(DATEDIFF(now(),a.F_CreatorTime) as signed) <=7 and cast(DATEDIFF(now(),a.F_CreatorTime) as signed)>=0 then 0 else 1 end reportState
                                from Site_Order_SalesReport a
                                inner join (select max(a.F_CreatorTime) F_CreatorTime,a.F_OrderId from Site_Order_SalesReport a group by a.F_OrderId) e on a.F_OrderId=e.F_OrderId and a.F_CreatorTime=e.F_CreatorTime
                                inner join Site_Client_Order b on a.F_OrderId=b.F_Id
                                inner join Site_Clients_ProjectByDemand c on b.F_DemandId=c.F_Id
                                inner join Sys_User d on a.F_CreatorUserId=d.F_Id where 1=1 {0} {1} {2} {3} {4} order by a.F_CreatorTime desc";
                var queryParam = queryJson.ToJObject();
               
                ///获取用户权限
                var LoginInfo = OperatorProvider.Provider.GetCurrent();
                RoleApp role = new RoleApp();
                RoleEntity roleEntity = role.GetForm(LoginInfo.RoleId);
                OrganizeApp organize = new OrganizeApp();
                OrganizeEntity organizeEntity = organize.GetForm(LoginInfo.DepartmentId);

                string F_GroupId = "";
                if(queryParam["F_Type"].ToString() != "self")
                {
                    if (roleEntity.F_EnCode == "1006" || roleEntity.F_EnCode == "1012")
                    {
                        F_GroupId += " and d.F_GroupId='" + LoginInfo.F_GroupId + "'";
                    }
                    else if (roleEntity.F_EnCode == "1004")
                    {
                        F_GroupId += " and d.F_GroupId='" + LoginInfo.F_GroupId + "' and d.F_Id='" + LoginInfo.F_GroupId + "'";
                    }
                }
                
                DbParameter[] parameter =
               {
                    new MySqlParameter("@F_StartTime", queryParam["F_StartTime"]),
                    new MySqlParameter("@F_EndTime", queryParam["F_EndTime"]),
                    new MySqlParameter("@F_Type",queryParam["F_Type"]),
                    new MySqlParameter("@F_DemandId",queryParam["F_DemandId"]),
                };

                sqlStr = string.Format(sqlStr, F_GroupId,
                    queryParam["F_StartTime"].IsEmpty() ? "" : " and a.F_CreatorTime>@F_StartTime",
                    queryParam["F_EndTime"].IsEmpty() ? "" : " and a.F_CreatorTime<@F_EndTime",
                    queryParam["F_Type"].ToString() == "self" ? " and a.F_CreatorUserId='" + LoginInfo.UserId + "'" : "",
                    queryParam["F_DemandId"].IsEmpty() ? "" : " and c.F_Id=@F_DemandId"
                    );
                reslut = db.FindList<OrderSalesReportViewModel>(sqlStr, parameter, pagination);
            }
            return reslut;
        }
    }
}
